<template>
  <div class="app-container">
    <div style="width: 20%">
      <categoryTree @tree-node-click="treeNodeClick"/>
    </div>
    <div style="width: 80%">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="属性名" prop="attrName">
          <el-input
            v-model="queryParams.attrName"
            placeholder="请输入属性名"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="启用状态" prop="enable">
          <el-select v-model="queryParams.enable" placeholder="请选择启用状态" clearable size="small">
            <el-option
              v-for="dict in enableOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="快速展示" prop="showDesc">
          <el-select v-model="queryParams.showDesc" placeholder="请选择快速展示" clearable size="small">
            <el-option
              v-for="dict in showDescOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button type="success" icon="el-icon-search" size="mini" @click="handleQueryAll">查询全部</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['attr:attr:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['attr:attr:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['attr:attr:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            :loading="exportLoading"
            @click="handleExport"
            v-hasPermi="['attr:attr:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="attrList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="属性id" align="center" prop="attrId" v-if="false"/>
        <el-table-column label="属性名" align="center" prop="attrName" />
        <el-table-column align="center" label="是否需要检索" prop="searchType" >
          <template slot-scope="scope">
            <i class="el-icon-success" v-if="scope.row.searchType==1"></i>
            <i class="el-icon-error" v-else></i>
          </template>
        </el-table-column>

        <el-table-column label="可选值列表" align="center" prop="valueSelect">
          <template slot-scope="scope">
            <el-tooltip placement="top">
              <div slot="content">
                <span v-if="scope.row.valueSelect.length>0" v-for="(i,index) in scope.row.valueSelect.toString().split(',')" :key="index">{{i}}<br/></span>
              </div>
              <el-tag v-if="scope.row.valueSelect.length==1">{{scope.row.valueSelect.toString().split(",")[0]}}</el-tag>
              <el-tag v-else="scope.row.valueSelect.length>1">{{scope.row.valueSelect.toString().split(",")[0]+" ..."}}</el-tag>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="启用状态" align="center" prop="enable" >
          <template slot-scope="scope">
            <i class="el-icon-success" v-if="scope.row.enable==1"></i>
            <i class="el-icon-error" v-else></i>
          </template>
        </el-table-column>
        <el-table-column label="所属分类" align="center" prop="catalogName" />
        <el-table-column label="快速展示" align="center" prop="showDesc">
          <template slot-scope="scope">
            <i class="el-icon-success" v-if="scope.row.showDesc==1"></i>
            <i class="el-icon-error" v-else></i>
          </template>
        </el-table-column>
        <el-table-column label="值类型" align="center" prop="valueType">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.valueType==1">允许多个值</el-tag>
            <el-tag v-else type="success">只能单个值</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['attr:attr:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['attr:attr:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 添加或修改商品属性对话框 -->
      <el-dialog :title="title" v-if="open" :close-on-click-modal="false" :visible.sync="open" width="650px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="110px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="属性名" prop="attrName">
                <el-input v-model="form.attrName" placeholder="请输入属性名" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="启用状态" prop="enable">
                <el-radio-group v-model="form.enable">
                  <el-radio
                    v-for="dict in enableOptions"
                    :key="dict.dictValue"
                    :label="parseInt(dict.dictValue)"
                  >{{dict.dictLabel}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="值类型" prop="valueType">
            <el-switch
              v-model="form.valueType"
              active-text="允许多个值"
              inactive-text="只能单个值"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :inactive-value="0"
              :active-value="1"
            ></el-switch>
          </el-form-item>

          <el-form-item label="可选值列表" prop="valueSelect">
            <el-select
              style="width: 400px"
              v-model="form.valueSelect"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请选择/输入">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="所属分类" prop="catalogId">
            <el-cascader
              filterable
              clearable
              size="medium"
              style="width: 400px"
              v-model="form.catalogId"
              :props="props"
              placeholder="试试搜索：手机"
              :options="categoryOptions"
              @change="handleChange"></el-cascader>
          </el-form-item>
          <el-form-item label="所属分组">
            <el-select v-model="form.attrGroupId" filterable placeholder="请选择">
              <el-option
                v-for="dict in attrGroupList"
                :key="dict.attrGroupId"
                :label="dict.attrGroupName"
                :value="dict.attrGroupId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item label="是否需要检索" prop="searchType">
                <el-radio-group v-model="form.searchType">
                  <el-radio
                    v-for="dict in searchTypeOptions"
                    :key="dict.dictValue"
                    :label="parseInt(dict.dictValue)"
                  >{{dict.dictLabel}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="快速展示" prop="showDesc">
                <el-radio-group v-model="form.showDesc">
                  <el-radio
                    v-for="dict in showDescOptions"
                    :key="dict.dictValue"
                    :label="parseInt(dict.dictValue)"
                  >{{dict.dictLabel}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>

</template>

<script>
  import { listAttr, getAttr, delAttr, addAttr, updateAttr, exportAttr } from "@/api/mall/pms/attr";
  import { getListByCatelogId } from "@/api/mall/pms/attrGroup";
  import categoryTree from '@/views/components/categoryTree';
  import { listCategory} from "@/api/mall/pms/category";
  export default {
    name: "Attr",
    components: {
      categoryTree
    },
    data() {
      return {
        options: [],
        //级联选择器
        props: {
          value: 'id',
          label: 'name',
          children: 'children'
        },
        //分组集合
        attrGroupList:[],
        //分类数据
        categoryOptions:[],
        //按钮loading
        buttonLoading: false,
        // 遮罩层
        loading: true,
        // 导出遮罩层
        exportLoading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 商品属性表格数据
        attrList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 是否需要检索字典
        searchTypeOptions: [],
        // 启用状态字典
        enableOptions: [],
        // 快速展示字典
        showDescOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          attrName: undefined,
          attrType: 2,//销售属性
          enable: undefined,
          catalogId: undefined,
          showDesc: undefined
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          attrName: [
            { required: true, message: "属性名不能为空", trigger: "blur" }
          ],
          searchType: [
            { required: true, message: "是否需要检索不能为空", trigger: "blur" }
          ],
          enable: [
            { required: true, message: "启用状态不能为空", trigger: "blur" }
          ],
          catalogId: [
            { required: true, message: "所属分类不能为空", trigger: "blur" }
          ],
          showDesc: [
            { required: true, message: "快速展示不能为空", trigger: "blur" }
          ],
          valueType: [
            { required: true, message: "值类型不能为空", trigger: "blur" }
          ]
        }
      };
    },
    created() {
      this.getList();
      this.getDicts("mall_nav_status").then(response => {
        this.searchTypeOptions = response.data;
      });
      this.getDicts("mall_nav_status").then(response => {
        this.enableOptions = response.data;
      });
      this.getDicts("mall_nav_status").then(response => {
        this.showDescOptions = response.data;
      });
    },
    methods: {
      //选择关联的分类
      handleChange(data){
        this.form.catalogId=data[data.length-1];
        this.getListByCatelogId(this.form.catalogId);

      },
      //按照分类id获取商品属性列表
      getListByCatelogId(catalogId){
        getListByCatelogId(catalogId).then(response => {
          this.attrGroupList=response.data;
        })
      },
      //级联选择器
      buildTree(){
        this.categoryOptions = [];
        listCategory().then(response => {
          this.categoryOptions = this.handleTree(response.data, "id", "parentId");
        })
      },
      //点击树节点查询
      treeNodeClick(data){
        if(data.level===3){
          this.queryParams.catalogId=data.id
          this.getList();
        }
      },
      /** 查询商品属性列表 */
      getList() {
        this.loading = true;
        listAttr(this.queryParams).then(response => {
          this.attrList = response.rows;
          this.total = response.total;
          this.loading = false;
        }).catch(() => {
          this.loading = false;
        });
      },
      // 是否需要检索字典翻译
      searchTypeFormat(row, column) {
        return this.selectDictLabel(this.searchTypeOptions, row.searchType);
      },
      // 启用状态字典翻译
      enableFormat(row, column) {
        return this.selectDictLabel(this.enableOptions, row.enable);
      },
      // 快速展示字典翻译
      showDescFormat(row, column) {
        return this.selectDictLabel(this.showDescOptions, row.showDesc);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          attrId: undefined,
          attrName: undefined,
          searchType: 0,
          icon: undefined,
          valueSelect: undefined,
          attrType: 2,
          enable: 0,
          catalogId: undefined,
          showDesc: 0
        };
        this.attrGroupList=[]
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      //搜索全部
      handleQueryAll(){
        this.queryParams.pageNum = 1;
        this.resetForm("queryForm");
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.attrId)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.form.enable=1
        this.form.showDesc=0
        this.buildTree();
        this.open = true;
        this.title = "添加商品属性";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.loading = true;
        this.reset();
        this.buildTree();
        const attrId = row.attrId || this.ids
        getAttr(attrId).then(response => {
          this.loading = false;
          this.form = response.data;
          this.getListByCatelogId(this.form.catalogId);
          this.form.catalogId=response.data.catalogIds;
          this.open = true;
          this.title = "修改商品属性";
        }).catch(() => {
          this.loading = false;
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          this.form.valueSelect=this.form.valueSelect.toString()
          //销售属性
          this.form.attrType=2;
          if (valid) {
            this.buttonLoading = true;
            if (this.form.attrId != null) {
              if(this.form.catalogId.length==3){
                this.form.catalogId=this.form.catalogId[this.form.catalogId.length-1];
              }
              updateAttr(this.form).then(response => {
                this.buttonLoading = false;
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }).catch(() => {
                this.buttonLoading = false;
              });
            } else {
              addAttr(this.form).then(response => {
                this.buttonLoading = false;
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }).catch(() => {
                this.buttonLoading = false;
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const attrIds = row.attrId || this.ids;
        this.$confirm('是否确认删除商品属性编号为"' + attrIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.loading = true;
          return delAttr(attrIds);
        }).then(() => {
          this.loading = false;
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {
          this.loading = false;
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有商品属性数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportAttr(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {
          this.exportLoading = false;
        });
      }
    }
  };
</script>
<style>
  .app-container{
    display: flex;
    justify-content: space-between;
  }
</style>
